package david.java.tools;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Stack;

/**
 * @Description:  对下面这种暂时不支持
 * ,bitmap_hash(concat(t.net_poi_id,sku.sku_id)) 	AS	`sku_id`
 * @Author: ZhaoDawei
 * @Date: Create in 4:26 下午 2022/4/24
 */
public class AsAlias {


    public static void main(String[] args) throws IOException {
        String input = "src/tmp/src_alias";
        String output = "target-tmp2/tmp-alias";
        mkdirIfNotExists(output);
        extract(input, output);

        new BitSet();
    }

    private static void mkdirIfNotExists(String path) {
        File file = new File(path);
        String parent = file.getParent();
        if (parent.equals("/")) {
            return;
        }
        boolean exists = file.getParentFile().exists();
        if (!exists) {
            file.getParentFile().mkdirs();
        }
    }

    private static void extract(String input, String output) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(input));
        BufferedWriter bw = new BufferedWriter(new FileWriter(output));
        List<String> result = new ArrayList<>();

        String line;
        while ((line = br.readLine()) != null) {
            if (StringUtils.isNotBlank(line) && !line.startsWith("--")) {

                String word = line.trim();
                if (!word.startsWith("--")) {
                    word = word + "\tAS\t" + getAlias(word);
                    result.add(word);
                }
            }
        }


        for (int i = 0; i < result.size(); i++) {
            bw.write(result.get(i));
            bw.newLine();
        }

        bw.flush();
        br.close();
        bw.close();
    }

    private static String getAlias(String line) {
        if (StringUtils.isBlank(line)) {
            return null;
        }
        String trim = line.trim();
        if (line.startsWith("--")) {
            return "注释";
        }
        Stack<Character> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        sb.append('`');
        char[] chars = trim.toCharArray();
        for (char c : chars) {
            if (c == ')') {
                break;
            }
            stack.add(c);
        }

        while (!stack.isEmpty()) {
            Character pop = stack.pop();
            if (pop == '.' || pop == '(') {
                break;
            }
            sb.append(pop);
        }

        return sb.append('`').reverse().toString();
    }

}
